package com.gzwanchuang.xhgj.ui.page.home;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;

import com.gzwanchuang.architecture.utils.FileUtils;
import com.gzwanchuang.architecture.utils.GsonUtils;
import com.gzwanchuang.architecture.utils.ImageUtils;
import com.gzwanchuang.architecture.utils.Utils;
import com.gzwanchuang.architecture.utils.ValidateUtils;
import com.gzwanchuang.xhgj.R;
import com.gzwanchuang.xhgj.bridge.request.LoginRequestViewModel;
import com.gzwanchuang.xhgj.bridge.state.home.ChangeJieSuanKaViewModel;
import com.gzwanchuang.xhgj.databinding.FragmentChangeJieSuanKaBinding;
import com.gzwanchuang.xhgj.help.ImageHelper;
import com.gzwanchuang.xhgj.help.PermissionHelper;
import com.gzwanchuang.xhgj.ui.base.BaseFragment;
import com.gzwanchuang.xhgj.ui.dialog.RecycleViewDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.List;

import kale.ui.view.dialog.EasyDialog;

import static android.app.Activity.RESULT_OK;

/**
 * 文件名 : HomeRootFragment
 * 创建者 : MangoWang
 * 创建日期 : 2019/12/24 16:20
 * 微信 : MangoWaWang
 * 邮箱 : 763482205@qq.com
 * 描述 : TODO
 */
public class ChangeJieSuanKaFragment extends BaseFragment {
    private FragmentChangeJieSuanKaBinding mBinding;
    private ChangeJieSuanKaViewModel mViewModel;
    private LoginRequestViewModel mRequestViewModel;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(ChangeJieSuanKaViewModel.class);
        mRequestViewModel = ViewModelProviders.of(this).get(LoginRequestViewModel.class);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_change_jie_suan_ka, container, false);
        mBinding = FragmentChangeJieSuanKaBinding.bind(view);
        mBinding.setClick(new ClickProxy());
        mBinding.setVm(mViewModel);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mRequestViewModel.getErrorString().observe(this, s -> {
            hideProgress();
            showShortToast(s);
        });  // 错误返回
        mRequestViewModel.getResultString().observe(this, s -> {
            hideProgress();
            showLongToast(s);
            nav().navigateUp();
        });
        mRequestViewModel.getCodeString().observe(this, s -> {
            showShortToast(s);
            hideProgress();
            mViewModel.startCode.set(true);
        });
        mRequestViewModel.getCompathone().observe(this, s -> {  // 上传第一步返回
            mViewModel.UploadPath = s;
            mRequestViewModel.upLoadImage(mViewModel.compressPathTwo.get(), mRequestViewModel.getCompathTwo());
        });
        mRequestViewModel.getCompathTwo().observe(this, s -> {  // 上传第二步返回
            mViewModel.UploadPathTwo = s;
            mRequestViewModel.upLoadImage(mViewModel.compressPathThree.get(), mRequestViewModel.getCompathThree());
        });
        mRequestViewModel.getCompathThree().observe(this, s -> {  // 上传第三步返回
            mViewModel.UploadPathThree = s;
            mRequestViewModel.audit(mViewModel.UploadPath, mViewModel.UploadPathTwo, mViewModel.UploadPathThree
                    , mViewModel.name.get(), mViewModel.bankCardCode.get(), mViewModel.phone.get(), mViewModel.code.get());
        });
        mRequestViewModel.getBanks().observe(this, banks -> {
            mViewModel.banks.addAll(banks);
        });

        mSharedViewModel.bankCardString.observe(this, s -> {
            if (mViewModel.selectImageType == 0) {
                mViewModel.compressPath.set(s);
            } else if (mViewModel.selectImageType == 1) {
                mViewModel.compressPathTwo.set(s);
            }
        });

        mRequestViewModel.get_support("1", "2");  // 类型:1-结算卡;2-信用卡   // VIP支持：1-支持;2-所有

    }

    public class ClickProxy {
        public void submit() {
            String name = mViewModel.name.get();
            if (TextUtils.isEmpty(name)) {
                showShortToast("请输入姓名");
                return;
            }
            String bankCardCode = mViewModel.bankCardCode.get();
            if (TextUtils.isEmpty(bankCardCode)) {
                showShortToast("请输入银行卡号码");
                return;
            }
            String phone = mViewModel.phone.get();
            if (TextUtils.isEmpty(phone)) {
                showShortToast("请输入银行预留手机号");
                return;
            }
            String code = mViewModel.code.get();
            if (TextUtils.isEmpty(code)) {
                showShortToast("请输入手机验证码");
                return;
            }
            showProgress();
            // 开始上传
            mRequestViewModel.upLoadImage(mViewModel.compressPath.get(), mRequestViewModel.getCompathone());
        }

        public void back() {
            nav().navigateUp();
        }

        public void checkBank() {
            if (ValidateUtils.isValidate(mViewModel.banks)) {
                RecycleViewDialog.Builder builder = new RecycleViewDialog.Builder(mActivity);
                builder.setData(GsonUtils.serializedToJson(mViewModel.banks)).setTitle("绑定结算卡支持银行");
                EasyDialog build = builder.build();
                build.show(getChildFragmentManager());
            } else {
                showShortToast("暂无支持银行");
            }
        }

        public void getCode() {
            String bankCardCode = mViewModel.bankCardCode.get();
            if (TextUtils.isEmpty(bankCardCode)) {
                showShortToast("请输入银行卡号码");
                return;
            }
            String mPhone = mViewModel.phone.get();
            if (TextUtils.isEmpty(mPhone)) {
                showShortToast("请输入手机号码");
                return;
            }
            if (mPhone.length() != 11) {
                showShortToast("请输入11位手机号码");
                return;
            }
            if (TextUtils.isEmpty(mPhone)) {
                showShortToast("请输入手机号码");
                return;
            }
            showProgress();
            mRequestViewModel.getSendcode(mPhone, bankCardCode);
        }

        public void selectPicture(int type) {
            mViewModel.selectImageType = type;
            PermissionHelper.getInstance().getPermission(mActivity, new PermissionHelper.PermissionCallBack() {
                @Override
                public void onSuccess() {
                    ImageHelper.showSelectChoose(ChangeJieSuanKaFragment.this);
                }

                @Override
                public void onFail() {
                    showShortToast("请先允许权限再使用此功能");
                }
            }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }

        public void selectBankCard(int type) {
            PermissionHelper.getInstance().getPermission(mActivity, new PermissionHelper.PermissionCallBack() {
                @Override
                public void onSuccess() {
                    mViewModel.selectImageType = type;
                    Bundle bundle = new Bundle();
                    bundle.putInt("type", 0);
                    nav().navigate(R.id.action_changeJieSuanKaFragment_to_takeCardPhotoFragment, bundle);
                }

                @Override
                public void onFail() {
                    showShortToast("请先允许权限再使用此功能");
                }
            }, Manifest.permission.WRITE_EXTERNAL_STORAGE);


        }
    }


    @Override
    public void onStop() {
        if (Utils.isAppForeground() || !mSharedViewModel.isLoading.getValue()) {
            mViewModel.startCode.set(false);
        }
        super.onStop();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == PictureConfig.CHOOSE_REQUEST) {
            List<LocalMedia> localMedias = PictureSelector.obtainMultipleResult(data);
            if (mViewModel.selectImageType == 2) {
                // 获取图片大小
                long length = FileUtils.getFileByPath(localMedias.get(0).getCompressPath()).length();
                if (length <= 307200L) { // 原图片的压缩小于300kb
                    mViewModel.compressPathThree.set(localMedias.get(0).getCompressPath());
                } else {

                }
            }
        }
    }
}
